import 'package:flutter/material.dart';

import '../../commons/log.dart';
import '../../commons/result.dart';
import '../models/catalog.dart';
import '../services/api/catalog_api_client.dart';
import '../services/api/models/catalog/catalog_response.dart';

class CatalogRepository {
  final _log = Log();
  final CatalogApiClient _catalogApiClient;

  CatalogRepository({required CatalogApiClient catalogApiClient})
      : _catalogApiClient = catalogApiClient;

  Future<Result<List<CatalogModel>>> getCatalog(int page) async {
    final response = await _catalogApiClient.getCatalog(page);
    if (response is Ok<List<CatalogResponse>?>) {
      final r = response as Ok<List<CatalogResponse>?>;
      final count = r.value?.length ?? 0;
      if (count == 0) {
        return Result.ok([]);
      } else {
        return Result.ok(r.value!
            .map(
              (e) => CatalogModel(
                id: e.id,
                name: e.name,
                price: e.price,
                color: Colors.primaries[e.id % Colors.primaries.length],
              ),
            )
            .toList());
      }
    } else if (response is Error<List<CatalogResponse>?>) {
      final r = response as Error<List<CatalogResponse>?>;
      return Result.error(r.error);
    } else {
      _log.error("Find catalog unknown error");
      return Result.error(Exception("Find catalog error"));
    }
  }
}
